import os
from django.shortcuts import render
from django.http import JsonResponse
from django.views.decorators.clickjacking import xframe_options_exempt
from common.ComHandler import get_random_name
from common.VerifyCodeHandler import verify_code
from user.login_views import check_login, User


# Create your views here.
@xframe_options_exempt
@check_login
def index(request):
    user = User.objects.filter(id=request.session.get("user_id"), is_delete=0).first()
    return render(request, 'index.html', {"user": user})


@xframe_options_exempt
@check_login
def index_page(request):
    return render(request, 'index_page.html')


@xframe_options_exempt
@check_login
def analysis_of_data(request):
    return render(request, 'bigdata.html')


def get_verify_code(request):
    result = {"status": 0, "msg": "验证码获取失败！"}
    try:
        file_name = verify_code()
        result["status"] = 1
        result["msg"] = "验证码获取成功！"
        result["file_url"] = file_name
    except Exception as e:
        print(e)
    return JsonResponse(result)


# 文件上传
@check_login
def upload(request):
    img_types = ["jpg", "png", "jpeg", "gif"]
    result = {"status": 0, "msg": "上传失败！"}
    try:
        base_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "static", "upload")
        file_url = ""
        if request.method == "POST":
            file = request.FILES.get("file")
            if not file:
                result["msg"] = "请上传文件"
                return JsonResponse(result)
            # print(file.name)
            # print(file.size)
            file_type = file.name.split(".")[1].lower()
            file_name = get_random_name(file_type)

            # 判断上传的文件类型是否是图片
            if file_type in img_types:
                with open(os.path.join(base_dir, "image", file_name), "wb") as f:
                    for line in file.chunks():
                        f.write(line)
                file_url = "http://127.0.0.1:8000" + "/static/upload/image/" + file_name

            result["status"] = 1
            result["msg"] = "上传成功！"
            result["file_url"] = file_url
    except Exception as e:
        print(e)
    return JsonResponse(result)


# 404
@xframe_options_exempt
@check_login
def page_not_found(request, exception):  # 注意点 ①
    return render(request, '404.html')


# 500
@xframe_options_exempt
@check_login
def page_error(request):
    return render(request, '500.html')
